# @Time    : 2025-07-17 11:43
# @Author  : strip
# @File    : main.py
# @Desc    : 程序入口


import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger

from app.api.v1.api import api_router
from app.core.config import settings
from app.db.base import init_db
from app.utils import http_error_handler, validation_error_handler
from app.core.scheduler import scheduler
# from utils.tools.redis import init_redis # (如果需要使用 Redis)


def add_event_handler(application: FastAPI) -> None:
    # 数据库连接/关闭
    init_db()
    # REDIS连接/关闭
    # init_redis(application)



def get_application() -> FastAPI:
    logger.debug(f"CONF:{settings.__dict__}")

    # 初始化 FastAPI app
    application = FastAPI(
        title=settings.PROJECT_NAME,
        debug=settings.DEBUG,
        version=settings.VERSION,
        lifespan=scheduler if settings.SCHEDULER_USE else None,  # 定时器(这里因为有两个地方的入口,不习惯可以用一个lifespan 管理)
    )

    # CORS 中间件配置
    application.add_middleware(
        CORSMiddleware,
        allow_origins=settings.ALLOWED_HOSTS,
        allow_credentials=True,
        allow_methods=settings.ALLOWED_METHODS,
        allow_headers=settings.ALLOWED_HEADERS,
    )
    # 载入数据库
    add_event_handler(application)
    # 异常处理
    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError, validation_error_handler)
    # 路由处理
    application.include_router(api_router, prefix="/api")

    return application


app = get_application()
if __name__ == "__main__":
    uvicorn.run(
        "main:app",  # 这里用字符串，格式为 "模块名:变量名"
        host="0.0.0.0",
        port=8000,
        log_level="info",
        reload=True,
    )
